(function() {
  "use strict";
  APP.Views.DialogPersonalizeView = Backbone.View.extend({
    el: '#modal',
    events : {
      'submit #personalizeTileForm': 'save',
      'click #removeBg': 'removeBg'
    },
    initialize: function(params) {
      this.appId = params.appId;
      this.appView = params.appView;
      var callback = {
        obj: this,
        name: 'getUserPulpitAppSuccess'
      }
      APP.BeClient.getUserPulpitApp(this.appId, callback);
    },
    getUserPulpitAppSuccess: function(data) {
      this.render(data.userPulpit);
    },
    removeBg: function(e) {
      e.preventDefault();
      this.$('#backgroundFilename').val('');
      this.$('#bgContainer img').attr('src', '');
      this.$('#bgContainer').hide(0);
    },
    save: function(e) {
      e.preventDefault();
      var data = $(e.currentTarget).serializeArray();
      if (data.length == 0) {
        $('#modal').modal('hide');
        return;
      }
      var callback = {
        obj: this,
        name: 'saveUserPulpitSuccess'
      }
      APP.BeClient.saveUserPulpit(this.appId, data, callback)
    },
    saveUserPulpitSuccess: function(data) {
      this.appView.setLayout(data.userPulpit);
      $('#modal').modal('hide');
      $('#menuBase').masonry('reload');
    },
    attachFileUploader: function() {
      var self = this;
      this.$("#backgroundFile").pekeUpload({
        theme:'bootstrap',
        showErrorAlerts: true,
        btnText: APP.getTrans('PERSONALIZE', 'BACKGROUND_BTN'),
        data: APP.User.get('id') + '/',
        onFileSuccess: function(file, data) {
          self.$('#bgContainer').show(0);
          self.$('.pekecontainer').html('');
          self.$('#backgroundFilename').val(data.path);
          self.$('#bgContainer img').attr('src', '/resources/background/' + data.path);
        }
      });
    },
    render: function(userPulpit) {
      this.$el.html(_.template($('#dialogPresonalizeTemplate').html(), {
        userPulpit: userPulpit,
        name: this.appView.application.name
      }));
      var input = this.$('input[name="size"][value="'+userPulpit.size+'"]');
      input.attr('selected', true);
      input.closest('label').addClass('active');
      this.attachFileUploader();
      this.$el.modal();
      return this;
    }
  });
}());